<template>
  <div class="customers-view">
    <h1>客户信息管理</h1>
    <div class="customer-controls">
      <div class="search-container">
        <input v-model="searchQuery" placeholder="搜索客户..." class="search-input">
        <button @click="showAddModal = true" class="add-button">
          + 添加客户
        </button>
      </div>
    </div>
    <div class="customer-list">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>电话</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="customer in filteredCustomers" :key="customer.userId">
            <td>{{ customer.userId }}</td>
            <td>{{ customer.username }}</td>
            <td>{{ customer.phone }}</td>
            <td class="actions">
              <button @click="editCustomer(customer)" class="edit-btn">编辑</button>
              <button @click="deleteCustomer(customer.userId)" class="delete-btn">删除</button>
              <router-link :to="`/customers/${customer.userId}`" class="detail-btn">详情</router-link>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- 添加/编辑客户模态框 -->
    <div v-if="showAddModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <h2>{{ editingCustomer? '编辑客户' : '添加新客户' }}</h2>
        <div class="form-group">
          <label>姓名</label>
          <input v-model="currentCustomer.username" type="text">
        </div>
        <div class="form-group">
          <label>电话</label>
          <input v-model="currentCustomer.phone" type="text">
        </div>
        <div class="modal-actions">
          <button @click="saveCustomer" class="save-btn">
            {{ editingCustomer? '更新' : '保存' }}
          </button>
          <button @click="closeModal" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'CustomersView',
  setup() {
    const customers = ref([]);
    const searchQuery = ref('');
    const showAddModal = ref(false);
    const editingCustomer = ref(null);
    const currentCustomer = ref({
      userId: null,
      username: '',
      phone: ''
    });

    // 创建axios实例
    const api = axios.create({
      baseURL: 'http://localhost:8080/healtheat208',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 从后端获取客户列表
    const fetchCustomers = async () => {
      try {
        const response = await api.get('/user/list');
        customers.value = response.data;
      } catch (error) {
        console.error('获取客户列表失败:', error);
        alert('获取客户列表失败，请稍后重试');
      }
    };

    // 组件挂载后加载数据
    onMounted(() => {
      fetchCustomers();
    });

    // 过滤客户
    const filteredCustomers = computed(() => {
      return customers.value.filter(customer => {
        return (
          (customer.username || '').includes(searchQuery.value) ||
          (customer.phone || '').includes(searchQuery.value)
        );
      });
    });

    // 保存客户（新增或更新）
    const saveCustomer = async () => {
      try {
        if (editingCustomer.value) {
          // 假设后端更新接口为 /user/update/{userId}
          await api.put(`/user/update/${currentCustomer.value.userId}`, currentCustomer.value);
          alert('客户信息更新成功');
        } else {
          // 假设后端新增接口为 /user/add
          await api.post('/user/add', currentCustomer.value);
          alert('客户添加成功');
        }
        await fetchCustomers(); // 刷新列表
        closeModal();
      } catch (error) {
        console.error('保存客户失败:', error);
        alert(`保存失败: ${error.response?.data?.message || error.message}`);
      }
    };

    // 编辑客户
    const editCustomer = (customer) => {
      currentCustomer.value = {
       ...customer
      };
      editingCustomer.value = true;
      showAddModal.value = true;
    };

    // 删除客户
    const deleteCustomer = async (id) => {
      if (confirm('确定要删除这个客户吗？')) {
        try {
          // 假设后端删除接口为 /user/delete/{userId}
          await api.delete(`/user/delete/${id}`);
          alert('客户删除成功');
          await fetchCustomers(); // 刷新列表
        } catch (error) {
          console.error('删除客户失败:', error);
          alert(`删除失败: ${error.response?.data?.message || error.message}`);
        }
      }
    };

    // 关闭模态框
    const closeModal = () => {
      showAddModal.value = false;
      editingCustomer.value = null;
      currentCustomer.value = {
        userId: null,
        username: '',
        phone: ''
      };
    };

    return {
      customers,
      searchQuery,
      filteredCustomers,
      showAddModal,
      editingCustomer,
      currentCustomer,
      editCustomer,
      deleteCustomer,
      saveCustomer,
      closeModal
    };
  }
}
</script>

<style scoped>
.customers-view {
  padding: 20px;
}

.customer-controls {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.search-container {
  display: flex;
  gap: 10px;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
}

.add-button {
  padding: 8px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-button:hover {
  background-color: #218838;
}

.customer-list table {
  width: 100%;
  border-collapse: collapse;
}

.customer-list th,
.customer-list td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.customer-list th {
  background-color: #f8f9fa;
}

.actions {
  display: flex;
  gap: 5px;
}

.edit-btn {
  padding: 5px 10px;
  background-color: #17a2b8;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.delete-btn {
  padding: 5px 10px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.detail-btn {
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  text-decoration: none;
  display: inline-block;
  margin-left: 5px;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 500px;
  max-width: 90%;
  position: relative;
}

.close {
  position: absolute;
  top: 10px;
  right: 20px;
  font-size: 24px;
  cursor: pointer;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group textarea {
  height: 80px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.save-btn {
  padding: 8px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  padding: 8px 16px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>